/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainJFrame.java
 *
 * Created on May 22, 2012, 9:47:08 AM
 */
package MyGUI;

import MyDatabaseHandler.DatabaseHandler;
import MyStatementExecution.MyStatement;
import MyStatementExecution.*;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import java.net.*;  
import java.io.*; 
import MyDataContainer.*;
import MyDataType.MyType;
import java.util.ArrayList;
/**
 *
 * @author Welcome
 */
public class MainJFrame extends javax.swing.JFrame {
    Socket s;
    /** Creates new form MainJFrame */
    public MainJFrame() {
        initComponents();
        
        myDatabaseList = new ArrayList<DatabaseHandler>();
        
        //Code cài đặt tree

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPaneListOfDatabase = new javax.swing.JScrollPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jButtonSelectAll = new javax.swing.JButton();
        jButtonSelect = new javax.swing.JButton();
        jButtonInsert = new javax.swing.JButton();
        jButtonUpdate = new javax.swing.JButton();
        jButtonDelete = new javax.swing.JButton();
        jButtonClear = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jButtonExecute = new javax.swing.JButton();
        jComboBoxDatabase = new javax.swing.JComboBox();
        jTextFieldIP = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButtonConnect = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenuFile = new javax.swing.JMenu();
        jMenuItemDisconnect = new javax.swing.JMenuItem();
        jMenuItemExit = new javax.swing.JMenuItem();
        jMenuEdit = new javax.swing.JMenu();
        jMenuItemAbout = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        jScrollPaneListOfDatabase.setBorder(javax.swing.BorderFactory.createTitledBorder("List of Database"));

        jTextArea2.setColumns(20);
        jTextArea2.setRows(5);
        jScrollPane2.setViewportView(jTextArea2);

        jButtonSelectAll.setText("Select *");
        jButtonSelectAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSelectAllActionPerformed(evt);
            }
        });

        jButtonSelect.setText("Select");
        jButtonSelect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSelectActionPerformed(evt);
            }
        });

        jButtonInsert.setText("Insert");
        jButtonInsert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonInsertActionPerformed(evt);
            }
        });

        jButtonUpdate.setText("Update");
        jButtonUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonUpdateActionPerformed(evt);
            }
        });

        jButtonDelete.setText("Delete");
        jButtonDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeleteActionPerformed(evt);
            }
        });

        jButtonClear.setText("Clear");
        jButtonClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonClearActionPerformed(evt);
            }
        });

        jButtonExecute.setText("Execute");
        jButtonExecute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExecuteActionPerformed(evt);
            }
        });

        jTextFieldIP.setText("127.0.0.1");

        jLabel1.setText("IP");

        jButtonConnect.setText("Connect");
        jButtonConnect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonConnectActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel2.setText("Java sql Client");

        jMenuFile.setText("File");

        jMenuItemDisconnect.setText("Disconnect");
        jMenuFile.add(jMenuItemDisconnect);

        jMenuItemExit.setText("Exit");
        jMenuItemExit.setActionCommand("");
        jMenuFile.add(jMenuItemExit);

        jMenuBar1.add(jMenuFile);

        jMenuEdit.setText("Edit");

        jMenuItemAbout.setText("About");
        jMenuEdit.add(jMenuItemAbout);

        jMenuBar1.add(jMenuEdit);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jComboBoxDatabase, javax.swing.GroupLayout.Alignment.TRAILING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPaneListOfDatabase, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(51, 51, 51)
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldIP))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGap(105, 105, 105)
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 291, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE)
                        .addComponent(jButtonConnect, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButtonSelectAll)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonSelect)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButtonInsert)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonUpdate)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonDelete)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonClear)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonExecute, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxDatabase, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButtonConnect)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButtonSelectAll)
                            .addComponent(jButtonSelect)
                            .addComponent(jButtonInsert)
                            .addComponent(jButtonUpdate)
                            .addComponent(jButtonDelete)
                            .addComponent(jButtonClear)
                            .addComponent(jButtonExecute))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE)
                        .addContainerGap())
                    .addComponent(jScrollPaneListOfDatabase, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 417, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonSelectAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSelectAllActionPerformed
            // TODO add your handling code here:
       jTextArea2.setText("SELECT * FROM thetindung WHERE 1");
    }//GEN-LAST:event_jButtonSelectAllActionPerformed

    private void jButtonSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSelectActionPerformed
            // TODO add your handling code here:
        jTextArea2.setText("SELECT a,b,c FROM x,y WHERE 1");
    }//GEN-LAST:event_jButtonSelectActionPerformed

    private void jButtonInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInsertActionPerformed
        // TODO add your handling code here:
        jTextArea2.setText("INSERT INTO table(a,b,c) VALUES (x,y,z)");
    }//GEN-LAST:event_jButtonInsertActionPerformed

    private void jButtonUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonUpdateActionPerformed
        // TODO add your handling code here:
        jTextArea2.setText("UPDATE table SET a=x,b=y,c=z WHERE 1");
    }//GEN-LAST:event_jButtonUpdateActionPerformed

    private void jButtonDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeleteActionPerformed
        // TODO add your handling code here:
         jTextArea2.setText("DELETE FROM table WHERE 1");
    }//GEN-LAST:event_jButtonDeleteActionPerformed

    private void jButtonClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonClearActionPerformed
        // TODO add your handling code here:
        jTextArea2.setText("");
    }//GEN-LAST:event_jButtonClearActionPerformed

private void jButtonExecuteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExecuteActionPerformed
// TODO add your handling code here:
    String queryString = jTextArea2.getText();
    int dbNameIndex = jComboBoxDatabase.getSelectedIndex();
    DatabaseHandler targetDB = myDatabaseList.get(dbNameIndex);
    
    targetDB.run(queryString);
    MyStatementKind kind = targetDB.getExecutionHandler().identifySqlStatement(queryString).getKind();
    if(kind==MyStatementKind.SELECT)
    {
            MyQuery selectQuery = targetDB.getExecutionHandler().getSelectQuery();
            loadSelectQueryIntoTable(selectQuery);
    }
}//GEN-LAST:event_jButtonExecuteActionPerformed

private void jButtonConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonConnectActionPerformed
// TODO add your handling code here:
    try
    {
    s = new Socket(jTextFieldIP.getText(), 2002);
    InputStream in = s.getInputStream();
    DataInputStream dis = new DataInputStream(in);
    int len = dis.readInt();
    byte[] bytes = new byte[len];
    if(len > 0)
    {
        dis.read(bytes, 0, len);
        System.out.print(bytes.length);
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInput oi = new ObjectInputStream(bis);
        DatabaseHandler o = (DatabaseHandler) oi.readObject(); 
        System.out.print(len);
        bis.close();
        in.close(); 
    }
    }
    catch(Exception e)
    {
        System.out.print(e.toString());
    }
}//GEN-LAST:event_jButtonConnectActionPerformed

private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
// TODO add your handling code here:
    addDatabaseFromDiskIntoList();
    loadListDatabaseTree();
    
}//GEN-LAST:event_formWindowActivated

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
       

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainJFrame().setVisible(true);
            }
        });
    }
    
    private ArrayList<DatabaseHandler> myDatabaseList;
    private static final String PATH_STRING =".\\src\\server\\Databases\\";
    private int selectedDB = 0;
        
    private void addDatabaseFromDiskIntoList()
    {
        //Load from disk
        //myDatabaseList.clear();
        File dirFile = new File(PATH_STRING);
        String[] dbList = dirFile.list();
        DatabaseHandler tempDBHandler=null;
        for(int i=0;i<dbList.length;i++)
        {
           
            tempDBHandler = new DatabaseHandler(PATH_STRING+dbList[i]);
            tempDBHandler.ReadDatabase();
            if(myDatabaseList.size()!=0)
            {
                 if(dbList.length !=  myDatabaseList.size())
                    {
                        myDatabaseList.add(tempDBHandler);
                        
                    }
            }
            else
            {
                myDatabaseList.add(tempDBHandler);
            }
      
        }
        
        
    }
    
    public void addDatabaseToList(String dbName)
    {
       
        DatabaseHandler temDatabaseHandler = new DatabaseHandler(PATH_STRING+"Testdb.xml");
        temDatabaseHandler.clearAll();
        temDatabaseHandler.setDatabaseName(dbName);
        temDatabaseHandler.WriteDatabase(PATH_STRING+dbName+".xml");
        myDatabaseList.add(temDatabaseHandler);
    }
    
    private void loadListDatabaseTree()
    {
        //jScrollPaneListOfDatabase.removeAll();
        DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Databases",true);
        for(int i=0; i<myDatabaseList.size();i++)
        {
            
            
            String databaseName = myDatabaseList.get(i).getDatabaseName();
    
            jComboBoxDatabase.addItem(databaseName);
            
            DefaultMutableTreeNode tempNode = new DefaultMutableTreeNode(databaseName,true);
            DefaultMutableTreeNode temp = new DefaultMutableTreeNode("Tables",true);
            tempNode.add(temp);
            String[] tableNames = myDatabaseList.get(i).getTableNames();
            
            for (int j=0; j<tableNames.length;j++)
            {
                DefaultMutableTreeNode temptable = new DefaultMutableTreeNode(tableNames[j],true);
                temp.add(temptable);
                MyDataString columnTitles = myDatabaseList.get(i).getTables().get(j).getColumnTitles();
                MyDataString dataTypeList = myDatabaseList.get(i).getTables().get(j).getDataTypeList();
                
                for (int k =0; k<columnTitles.getSize();k++)
                {
                    DefaultMutableTreeNode tempColumn = new DefaultMutableTreeNode(columnTitles.getAt(k)+" ("+dataTypeList.getAt(k)+")",true);
                    temptable.add(tempColumn);
                }
            }
            
            parent.add(tempNode);
        }
        
        JTree dbTree = new JTree(parent);
            
        jScrollPaneListOfDatabase.setViewportView(dbTree);
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonClear;
    private javax.swing.JButton jButtonConnect;
    private javax.swing.JButton jButtonDelete;
    private javax.swing.JButton jButtonExecute;
    private javax.swing.JButton jButtonInsert;
    private javax.swing.JButton jButtonSelect;
    private javax.swing.JButton jButtonSelectAll;
    private javax.swing.JButton jButtonUpdate;
    private javax.swing.JComboBox jComboBoxDatabase;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenu jMenuEdit;
    private javax.swing.JMenu jMenuFile;
    private javax.swing.JMenuItem jMenuItemAbout;
    private javax.swing.JMenuItem jMenuItemDisconnect;
    private javax.swing.JMenuItem jMenuItemExit;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPaneListOfDatabase;
    private javax.swing.JTextArea jTextArea2;
    private javax.swing.JTextField jTextFieldIP;
    // End of variables declaration//GEN-END:variables

    private void loadSelectQueryIntoTable(MyQuery selectQuery) {
        MyDataString columnTitles = selectQuery.getColumnTitles();
        
        String[] columnNames = columnTitles.getAllData();
        ArrayList<MyDataSet> rowContents = selectQuery.getRowContents();
        
        Object[][] data = new Object[rowContents.size()][];
        for(int i=0; i<rowContents.size();i++)
        {
            String[] temp = rowContents.get(i).getData();
            data[i] = temp;
        }
        JTable table = new JTable(data, columnNames);

        jScrollPane3.setViewportView(table);
        

        jScrollPane3.setViewportView(table);
    }
}
